<template>
  <view class="filter-bar-container">
    <view class="filter-bar">
      <view v-for="(item, index) in visibleFilters" :key="index" class="filter-item" @click="onFilterClick(item.type)">
        <text>{{ item.text }}</text>
        <uni-icons :type="selectedValues[item.type] ? 'up' : 'down'" size="14"
          :color="selectedValues[item.type] ? '#1890ff' : '#666'">
        </uni-icons>
      </view>
    </view>

    <!-- 修改级联选择器弹出方式 -->
    <view class="popup-content cascade-popup" v-show="currentFilter?.type === 'department' && popupVisible">
      <view class="popup-header">
        <view class="header-item">部门</view>
        <view class="header-item">人员</view>
      </view>
      <view class="cascade-content">
        <scroll-view scroll-y class="cascade-left">
          <view v-for="(item, index) in currentOptions" :key="index"
            :class="['cascade-item', { active: currentLevel1 === index || (index === 0 && currentLevel1 === -1) }]"
            @click="selectLevel1(index)">
            {{ item.label }}
          </view>
        </scroll-view>
        <scroll-view scroll-y class="cascade-right">
          <view class="cascade-item" :class="{ active: currentLevel2 === -1 }" @click="selectLevel2(-1)">
            全部
          </view>
          <template v-if="level2Options.length">
            <view v-for="(item, index) in level2Options" :key="index"
              :class="['cascade-item', { active: currentLevel2 === index }]" @click="selectLevel2(index)">
              {{ item.label }}
            </view>
          </template>
        </scroll-view>
      </view>
      <view class="popup-footer">
        <button class="btn-reset" @click="resetFilter">重置</button>
        <button class="btn-confirm" @click="confirmFilter">确定</button>
      </view>
    </view>

    <!-- 修改状态选择器弹出方式 -->
    <view class="popup-content status-popup" v-show="currentFilter?.type === 'status' && popupVisible">
      <scroll-view scroll-y class="status-scroll">
        <view v-for="(group, index) in currentOptions" :key="index" class="status-group">
          <view class="group-title">{{ group.title }}</view>
          <view class="group-content">
            <view v-for="(item, idx) in group.options" :key="idx"
              :class="['status-item', { active: isSelected(item.value, group.type) }]"
              @click="selectStatus(item, group.type)">
              {{ item.label }}
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="popup-footer">
        <button class="btn-reset" @click="resetFilter">重置</button>
        <button class="btn-confirm" @click="confirmFilter">确定</button>
      </view>
    </view>

    <!-- 修改筛选面板弹出方式 -->
    <view class="popup-content filter-popup" v-show="currentFilter?.type === 'filter' && popupVisible">
      <scroll-view scroll-y class="filter-scroll">
        <view v-for="(group, index) in currentOptions" :key="index" class="filter-group">
          <view class="group-title">{{ group.title }}</view>
          <view class="group-content">
            <view v-for="(item, idx) in group.options" :key="idx"
              :class="['filter-item', { active: isSelected(item.value, group.type) }]"
              @click="selectFilter(item, group.type)">
              {{ item.label }}
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="popup-footer">
        <button class="btn-reset" @click="resetFilter">重置</button>
        <button class="btn-confirm" @click="confirmFilter">确定</button>
      </view>
    </view>

    <!-- 添加合同状态弹出层 -->
    <view class="popup-content contract-status-popup" v-show="currentFilter?.type === 'contractStatus' && popupVisible">
      <scroll-view scroll-y class="contract-status-scroll">
        <view class="contract-status-list">
          <view v-for="(item, index) in currentOptions" :key="index"
            :class="['contract-status-item', { active: tempSelected === item.value }]"
            @click="selectContractStatus(item)">
            {{ item.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 添加待收账单弹出层 -->
    <view class="popup-content bill-type-popup" v-show="currentFilter?.type === 'billType' && popupVisible">
      <scroll-view scroll-y class="bill-type-scroll">
        <view class="bill-type-list">
          <view v-for="(item, index) in currentOptions" :key="index"
            :class="['bill-type-item', { active: tempSelected === item.value }]" @click="selectBillType(item)">
            {{ item.label }}
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 添加排序弹出层 -->
    <view class="popup-content sort-popup" v-show="currentFilter?.type === 'sort' && popupVisible">
      <view class="sort-list">
        <view class="sort-tags">
          <uni-tag text="默认排序" :type="tempSelected === 'default' || tempSelected === null ? 'primary' : 'default'"
            :inverted="tempSelected === 'default' || tempSelected === null"
            @click="selectSort({ value: 'default', label: '默认排序' })">
          </uni-tag>
          <uni-tag text="空置天数" :type="tempSelected === 'emptyDays' ? 'primary' : 'default'"
            :inverted="tempSelected === 'emptyDays'" @click="selectSort({ value: 'emptyDays', label: '空置天数' })">
          </uni-tag>
        </view>
      </view>
    </view>
    <!-- 添加遮罩层 -->
    <view class="popup-mask" v-show="popupVisible" @click="closeAllPopups"></view>
  </view>
</template>

<script>
export default {
  name: 'FilterBar',
  props: {
    filters: {
      type: Array,
      default: () => []
    },
    filterData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      filterTypes: {
        department: { text: '部门', type: 'cascade' },
        status: { text: '状态', type: 'status' },
        filter: { text: '筛选', type: 'filter' },
        contractStatus: { text: '合同状态', type: 'contractStatus' },
        billType: { text: '账单类型', type: 'billType' },
        sort: { text: '排序', type: 'sort' }
      },
      popupVisible: false, // 添加弹出层显示状态
      currentFilter: null,
      currentOptions: [],
      currentLevel1: -1,
      currentLevel2: -1,
      selectedValues: {},
      tempSelected: null
    }
  },
  computed: {
    visibleFilters() {
      return this.filters.map(type => ({
        type,
        text: this.filterTypes[type]?.text || type
      }))
    },
    level2Options() {
      if (this.currentLevel1 === -1) return []
      return this.currentOptions[this.currentLevel1]?.children || []
    }
  },
  mounted() {
    // 初始化部门选择器的默认值
    if (this.filters.includes('department')) {
      this.currentFilter = { ...this.filterTypes.department, type: 'department' }
      this.currentOptions = this.filterData.department || []
      this.currentLevel1 = 0
      this.currentLevel2 = -1

      // 如果有数据，则确认选择
      if (this.currentOptions.length > 0) {
        this.confirmFilter()
      }
    }
  },

  methods: {
    /**
     * 点击筛选项时触发
     * @param {string} type - 筛选类型（如：department, status, filter等）
     */
    onFilterClick(type) {
      const filterConfig = this.filterTypes[type]

      // 如果当前点击的是已经打开的筛选项，则关闭它
      if (this.currentFilter?.type === type && this.popupVisible) {
        this.popupVisible = false;
        this.currentFilter = null;
        return;
      }

      // 设置当前筛选项和选项数据
      this.currentFilter = { ...filterConfig, type }
      this.currentOptions = this.filterData[type] || []

      // 如果是部门选择器，设置默认值或恢复保存的选择
      if (type === 'department') {
        const savedSelection = this.selectedValues[type]
        if (savedSelection) {
          // 恢复保存的选择
          this.currentLevel1 = this.currentOptions.findIndex(
            item => item.value === savedSelection.level1.value
          )
          this.currentLevel2 = -1  // 默认选中"全部"
        } else {
          // 没有保存的选择，设置默认值
          this.currentLevel1 = 0
          this.currentLevel2 = -1
        }
      }

      // 如果是状态或筛选选择器，恢复之前的临时选择
      if (['status', 'contractStatus', 'billType', 'sort', 'filter'].includes(type)) {
        this.tempSelected = this.selectedValues[type] || null;
      }
      // 排序选择器特殊处理，默认选中"默认排序"
      if (type === 'sort') {
        this.tempSelected = this.selectedValues[type] || 'default';
      }

      // 合同状态选择器特殊处理，如果没有选中项，默认选中第一项
      if (type === 'contractStatus' && !this.selectedValues[type] && this.currentOptions.length > 0) {
        this.tempSelected = this.currentOptions[0].value;
      }

      // 待收账单选择器特殊处理，如果没有选中项，默认选中第一项
      if (type === 'billType' && !this.selectedValues[type] && this.currentOptions.length > 0) {
        this.tempSelected = this.currentOptions[0].value;
      }
      // 显示弹出层
      this.popupVisible = true;
    },

    // 关闭所有弹出层
    closeAllPopups() {
      this.popupVisible = false;
      this.tempSelected = null;
    },
    /**
     * 选择级联选择器的一级选项
     * @param {number} index - 选中项的索引
     */
    selectLevel1(index) {
      this.currentLevel1 = index
      this.currentLevel2 = -1  // 切换一级选项时，二级选项默认选中"全部"
    },
    /**
    * 确认筛选条件
    * 处理不同类型选择器的选中结果，并触发filter-change事件
    */
    confirmFilter() {
      let result = null

      if (this.currentFilter.type === 'cascade' && this.currentLevel1 !== -1) {
        const level1 = this.currentOptions[this.currentLevel1]
        result = {
          level1: { value: level1.value, label: level1.label },
          level2: null  // 默认为 null，表示选中"全部"
        }
        if (this.currentLevel2 !== -1) {  // 只有选择具体选项时才设置 level2
          const level2 = level1.children[this.currentLevel2]
          result.level2 = { value: level2.value, label: level2.label }
        }
      } else {
        result = this.tempSelected
      }

      this.selectedValues[this.currentFilter.type] = result
      this.$emit('filter-change', {
        type: this.currentFilter.type,
        value: result
      })

      this.closePopup(this.currentFilter.type)
    },

    /**
     * 选择级联选择器的二级选项
     * @param {number} index - 选中项的索引，-1表示选择"全部"
     */
    selectLevel2(index) {
      this.currentLevel2 = index
    },

    /**
     * 选择状态面板中的选项
     * @param {Object} item - 选中的选项，包含value和label
     * @param {string} groupType - 选项所属的分组类型
     */
    selectStatus(item) {
      if (!this.tempSelected) this.tempSelected = {}
      this.tempSelected[groupType] = item.value
    },

    /**
     * 选择筛选面板中的选项
     * @param {Object} item - 选中的选项，包含value和label
     * @param {string} groupType - 选项所属的分组类型
     */
    selectFilter(item, groupType) {
      if (!this.tempSelected) this.tempSelected = {}
      this.tempSelected[groupType] = item.value
    },

    /**
        * 选择合同状态选项
        * @param {Object} item - 选中的选项，包含value和label
        */
    selectContractStatus(item) {
      this.tempSelected = item.value;
      this.confirmFilter();
    },

    /**
        * 选择待收账单选项
        * @param {Object} item - 选中的选项，包含value和label
        */
    selectBillType(item) {
      this.tempSelected = item.value;
      this.confirmFilter();
    },

    /**
    * 选择排序选项
    * @param {Object} item - 选中的选项，包含value和label
    */
    selectSort(item) {
      this.tempSelected = item.value;
      this.confirmFilter();
    },

    /**
     * 判断选项是否被选中
     * @param {string|number} value - 选项的值
     * @param {string} [groupType] - 选项所属的分组类型（可选）
     * @returns {boolean} 是否选中
     */
    isSelected(value, groupType) {
      if (groupType) {
        return this.tempSelected?.[groupType] === value
      }
      return this.tempSelected === value
    },

    /**
     * 重置筛选条件
     * 部门选择器：重置为默认部门
     * 其他选择器：清空选择
     */
    resetFilter() {
      if (this.currentFilter.type === 'cascade') {
        // 先设置选中总部
        this.currentLevel1 = 0
        this.currentLevel2 = -1
        // 确认选择以触发更新
        this.confirmFilter()
      } else {
        // 其他选择器的逻辑保持不变
        this.tempSelected = null
        this.currentLevel1 = -1
        this.currentLevel2 = -1
      }
    },

    /**
     * 确认筛选条件
     * 处理不同类型选择器的选中结果，并触发filter-change事件
     */
    confirmFilter() {
      let result = null

      if (this.currentFilter.type === 'cascade' && this.currentLevel1 !== -1) {
        const level1 = this.currentOptions[this.currentLevel1]
        result = {
          level1: { value: level1.value, label: level1.label },
          level2: null
        }
        if (this.currentLevel2 !== -1 && level1.children) {  // 只有当不是选择"全部"时才设置 level2
          const level2 = level1.children[this.currentLevel2]
          result.level2 = { value: level2.value, label: level2.label }
        }
      } else {
        result = this.tempSelected
      }

      this.selectedValues[this.currentFilter.type] = result
      this.$emit('filter-change', {
        type: this.currentFilter.type,
        value: result
      })

      this.closePopup(this.currentFilter.type)
    },

    /**
     * 关闭弹出层
     * @param {string} type - 要关闭的弹出层类型
     */
    closePopup(type) {
      this.popupVisible = false;
      this.tempSelected = null;
    }
  }
}
</script>

<style lang="scss">
.filter-bar-container {
  position: relative;
  z-index: 999; // 确保在页面其他元素上方
  display: flex;
  flex-direction: column; // 使用列式布局，让弹出层自然排列在筛选栏下方
}

.filter-bar {
  display: flex;
  align-items: center;
  height: 80rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: relative; // 添加相对定位
  z-index: 999; // 确保在页面其他元素上方

  .filter-item {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    color: #333;
    position: relative;

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 1rpx;
      height: 24rpx;
      background-color: #eee;
    }

    text {
      margin-right: 8rpx;
    }
  }
}

// 添加弹出层样式
.popup-content {
  position: absolute; // 改为绝对定位
  top: 80rpx; // 从筛选栏下方开始
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 1000; // 确保在遮罩层上方
}

.popup-header {
  display: flex;
  border-bottom: 1rpx solid #eee;
  background-color: #f5f5f5;

  .header-item {
    width: 50%;
    text-align: left;
    padding: 10rpx 30rpx; // 减小上下间距，保持左右间距
    font-size: 28rpx;
    font-weight: bold;
  }
}

.popup-footer {
  display: flex;
  padding: 20rpx;
  border-top: 1rpx solid #eee;

  button {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 28rpx;
    margin: 0 10rpx;
    // 移除 border-radius: 40rpx;

    &.btn-reset {
      background-color: #f5f5f5;
      color: #666;
    }

    &.btn-confirm {
      background-color: #1890ff;
      color: #fff;
    }
  }
}

.cascade-popup {
  .cascade-content {
    display: flex;
    height: 600rpx;

    .cascade-left {
      width: 50%;
      height: 100%;
      background-color: #f5f5f5;
    }

    .cascade-right {
      width: 50%;
      height: 100%;
    }

    .cascade-item {
      padding: 16rpx 30rpx; // 修改上下间距为 16rpx
      font-size: 26rpx;
      color: #333;

      &.active {
        background-color: #fff;
        color: #1890ff;
      }
    }
  }
}

.status-popup {
  height: 800rpx;
  display: flex;
  flex-direction: column;

  .status-scroll {
    flex: 1;
    padding: 30rpx;
  }

  .status-group {
    margin-bottom: 30rpx;

    .group-title {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .group-content {
      display: flex;
      flex-wrap: wrap;

      .status-item {
        padding: 12rpx 24rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 10rpx;
        font-size: 26rpx;
        color: #333;

        &.active {
          background-color: #e6f7ff;
          color: #1890ff;
        }
      }
    }
  }
}

.filter-popup {
  height: 800rpx;
  display: flex;
  flex-direction: column;

  .filter-scroll {
    flex: 1;
    padding: 30rpx;
  }

  .filter-group {
    margin-bottom: 30rpx;

    .group-title {
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }

    .group-content {
      display: flex;
      flex-wrap: wrap;

      .filter-item {
        padding: 12rpx 24rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        margin: 10rpx;
        font-size: 26rpx;
        color: #333;

        &.active {
          background-color: #e6f7ff;
          color: #1890ff;
        }
      }
    }
  }
}

.contract-status-popup {
  max-height: 600rpx;

  .contract-status-scroll {
    height: 100%;
  }

  .contract-status-list {
    padding: 20rpx 0;

    .contract-status-item {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20rpx 30rpx;
      font-size: 28rpx;
      color: #333;

      &.active {
        color: #1890ff;
      }
    }
  }
}

//账单类型选择器
.bill-type-popup {
  height: auto; // 添加自适应高度

  .bill-type-scroll {
    height: auto; // 添加自适应高度
  }

  .bill-type-list {
    padding: 20rpx 0;

    .bill-type-item {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20rpx 30rpx;
      font-size: 28rpx;
      color: #333;

      &.active {
        color: #1890ff;
      }
    }
  }
}

.sort-list {
  padding: 20rpx 30rpx;

  .sort-tags {
    display: flex;
    flex-direction: row;
    gap: 20rpx;
  }
}

// 添加遮罩层样式
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 998; // 确保在筛选栏下方，弹出内容上方
}
</style>